package tcpGroupChat;

import java.io.*;
import java.net.Socket;

public class ServerReadThread extends Thread {

    private Socket socket;

    public ServerReadThread(Socket socket) {
        this.socket = socket;
    }
    public ServerReadThread() {

    }

    public void run(){
        try {
            //从端点socket得到一个字节流
            InputStream inputStream = socket.getInputStream();
            //把字节流包装成数据流
            DataInputStream dataInputStream = new DataInputStream(inputStream);
            while (true) {
                try {
                    //使用数据流读取客户端数据
                    String s = dataInputStream.readUTF();
                    System.out.println(s);
                    //当读取到客户端传来的消息后，发送给在线的所有客户端（包括自己）
                    sendMessage(s);
                } catch (IOException e) {
                    System.out.println("ip地址为" + socket.getRemoteSocketAddress() + "下线了！！！");
                    Server.onLineList.remove(socket);
                    dataInputStream.close();
                    socket.close();
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void sendMessage(String message) throws IOException {
        for (Socket so : Server.onLineList) {
            //从socket获取一个输出流
            OutputStream outputStream = so.getOutputStream();
            //包装成高级数据流
            DataOutputStream dataOutputStream = new DataOutputStream(outputStream);
            //将其消息写给通信管道
            dataOutputStream.writeUTF(message);
            //刷新数据，防止没有发出去消息
            dataOutputStream.flush();
        }
    }

}
